package com.tozed.android.launcher.simpleui;

import java.util.ArrayList;
import java.util.Locale;

import com.tozed.android.launcher.LauncherApplication;
import com.tozed.android.launcher.R;

import android.app.ActivityOptions;
import android.content.ActivityNotFoundException;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BlurMaskFilter;
import android.graphics.Canvas;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PaintFlagsDrawFilter;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.TableMaskFilter;
import android.graphics.Bitmap.Config;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.PaintDrawable;
import android.net.Uri;
import android.provider.BaseColumns;
import android.provider.CallLog;
import android.provider.CallLog.Calls;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityManager;
import android.widget.Toast;
import android.widget.ImageView.ScaleType;

public class SimpleUtilities
{
	private static final String TAG = "SimpleUtilities";
	private static final Paint sBlurPaint;
	private static final Canvas sCanvas;
	static int sColorIndex;
	static int[] sColors;
	private static final Paint sDisabledPaint;
	private static final Paint sGlowColorFocusedPaint;
	private static final Paint sGlowColorPressedPaint;
	private static int sIconHeight;
	private static int sIconTextureHeight;
	private static int sIconTextureWidth;
	private static int sIconWidth = -1;
	private static final Rect sOldBounds;
	
	private static final String INTENT_EXTRA_IGNORE_LAUNCH_ANIMATION =
            "com.android.launcher.intent.extra.shortcut.INGORE_LAUNCH_ANIMATION";
	
	static
	{
		sIconHeight = -1;
		sIconTextureWidth = -1;
		sIconTextureHeight = -1;
		sBlurPaint = new Paint();
		sGlowColorPressedPaint = new Paint();
		sGlowColorFocusedPaint = new Paint();
		sDisabledPaint = new Paint();
		sOldBounds = new Rect();
		sCanvas = new Canvas();
		//sCanvas.setDrawFilter(new PaintFlagsDrawFilter(4, 2));
		sCanvas.setDrawFilter(new PaintFlagsDrawFilter(Paint.DITHER_FLAG, Paint.FILTER_BITMAP_FLAG));
		//sColors = new int[] { -65536, -16711936, -16776961 };
		sColors = new int[] { 0xffff0000, 0xff00ff00, 0xff0000ff };
		sColorIndex = 0;
	}
	
	private static void initStatics(Context context)
	{
	    synchronized (sCanvas){
	      Resources res = context.getResources();
	      float density = res.getDisplayMetrics().density;
	      
	      sIconWidth = sIconHeight = (int)res.getDimension(R.dimen.simple_app_icon_size);
	      sIconTextureWidth = sIconTextureHeight = sIconWidth;
	      
	      sBlurPaint.setMaskFilter(new BlurMaskFilter(5 * density, BlurMaskFilter.Blur.NORMAL));
	      sGlowColorPressedPaint.setColor(0xffffc300);
	      sGlowColorFocusedPaint.setColor(0xffff8e00);
	      sGlowColorPressedPaint.setMaskFilter(TableMaskFilter.CreateClipTable(0, 30));
	      sGlowColorFocusedPaint.setMaskFilter(TableMaskFilter.CreateClipTable(0, 30));
	      
	      ColorMatrix colorMatrix = new ColorMatrix();
	      colorMatrix.setSaturation(0.2F);
	      
	      sDisabledPaint.setColorFilter(new ColorMatrixColorFilter(colorMatrix));
	      sDisabledPaint.setAlpha(0x88);
	    }
	 }
	
	static int getIconWidth(Context paramContext)
	{
		synchronized (sCanvas){
			if (sIconWidth == -1)
				initStatics(paramContext);
			return sIconWidth;
		}
	}
	
	static Bitmap getMaskBitmap(int resId)
	{
		Drawable drawable = LauncherApplication.getActiveInstance().getResources().getDrawable(resId);
		
		Bitmap bmp = Bitmap.createBitmap(drawable.getIntrinsicWidth(),drawable.getIntrinsicHeight(), 
				Bitmap.Config.ARGB_8888);
		
		Canvas canvas = new Canvas(bmp);
		drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
		drawable.draw(canvas);
		
		return bmp;
	}
	
	// 对两个位图做一个遮罩的效果
	public static Bitmap mask(Bitmap sourceBmp, Bitmap maskBmp)
	{
		// TODO: 
	    return sourceBmp;
	}
	
	public static Bitmap bitmapMask(Bitmap sourceBmp, Bitmap maskBmp)
	{
		//获取图片的资源文件
		final Bitmap original = sourceBmp;
		//获取遮罩层图片
		final Bitmap mask = maskBmp;
		
		Bitmap result = Bitmap.createBitmap(mask.getWidth(), mask.getHeight(), Config.ARGB_8888);
	     //将遮罩层的图片放到画布中
		Canvas mCanvas = new Canvas(result);
		Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
		paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));//叠加重复的部分，显示下面的
		mCanvas.drawBitmap(original, 0, 0, null);
		mCanvas.drawBitmap(mask, 0, 0, paint);
		paint.setXfermode(null);
		
		return result;
	}
	
    /**
     * Returns a bitmap suitable for the all apps view.
     */
    public static Bitmap createIconBitmap(Drawable icon, Context context) {
        synchronized (sCanvas) { // we share the statics :-(
            if (sIconWidth == -1) {
                initStatics(context);
            }

            int width = sIconWidth;
            int height = sIconHeight;

            if (icon instanceof PaintDrawable) {
                PaintDrawable painter = (PaintDrawable) icon;
                painter.setIntrinsicWidth(width);
                painter.setIntrinsicHeight(height);
            } else if (icon instanceof BitmapDrawable) {
                // Ensure the bitmap has a density.
                BitmapDrawable bitmapDrawable = (BitmapDrawable) icon;
                Bitmap bitmap = bitmapDrawable.getBitmap();
                if (bitmap.getDensity() == Bitmap.DENSITY_NONE) {
                    bitmapDrawable.setTargetDensity(context.getResources().getDisplayMetrics());
                }
            }
            int sourceWidth = icon.getIntrinsicWidth();
            int sourceHeight = icon.getIntrinsicHeight();
            if (sourceWidth > 0 && sourceHeight > 0) {
                // There are intrinsic sizes.
                if (width < sourceWidth || height < sourceHeight) {
                    // It's too big, scale it down.
                    final float ratio = (float) sourceWidth / sourceHeight;
                    if (sourceWidth > sourceHeight) {
                        height = (int) (width / ratio);
                    } else if (sourceHeight > sourceWidth) {
                        width = (int) (height * ratio);
                    }
                } else if (sourceWidth < width && sourceHeight < height) {
                    // Don't scale up the icon
                    width = sourceWidth;
                    height = sourceHeight;
                }
            }

            // no intrinsic size --> use default size
            int textureWidth = sIconTextureWidth;
            int textureHeight = sIconTextureHeight;

            final Bitmap bitmap = Bitmap.createBitmap(textureWidth, textureHeight,
                    Bitmap.Config.ARGB_8888);
            final Canvas canvas = sCanvas;
            canvas.setBitmap(bitmap);

            final int left = (textureWidth-width) / 2;
            final int top = (textureHeight-height) / 2;

            @SuppressWarnings("all") // suppress dead code warning
            final boolean debug = false;
            if (debug) {
                // draw a big box for the icon for debugging
                canvas.drawColor(sColors[sColorIndex]);
                if (++sColorIndex >= sColors.length) sColorIndex = 0;
                Paint debugPaint = new Paint();
                debugPaint.setColor(0xffcccc00);
                canvas.drawRect(left, top, left+width, top+height, debugPaint);
            }

            sOldBounds.set(icon.getBounds());
            icon.setBounds(left, top, left+width, top+height);
            icon.draw(canvas);
            icon.setBounds(sOldBounds);
            canvas.setBitmap(null);

            return bitmap;
        }
    }
	
	// 创建缩放图标
	public static Bitmap createScaledIconBitmap(Bitmap bmp, int targetWidth, int targetHeight)
	{
		if (bmp == null)
			return null;
		
		int width = bmp.getWidth();
		int heiht = bmp.getHeight();
		
		float scaleX = ((float)targetWidth / width);
		float scaleY = ((float)targetHeight / heiht);
		
		Matrix matrix = new Matrix();
		matrix.reset(); // 关键, 把原始类恢复到最初状态
		matrix.setScale(scaleX, scaleY);	
		
		return Bitmap.createBitmap(bmp, 0, 0, width, heiht, matrix, true);
	}
	
	public static Bitmap makeDefaultIcon(Context context, int resId)
	{
		Resources resources = context.getResources();
		Drawable dawable;
		
		if (-1 != resId){
			dawable = resources.getDrawable(resId);
		}else{
			dawable = resources.getDrawable(R.drawable.ic_default_icon);
		}
		
		try
		{
			int width = Math.max(dawable.getIntrinsicWidth(), 1);
			int height = Math.max(dawable.getIntrinsicHeight(), 1);
			
			Bitmap newBmp = Bitmap.createBitmap(width,height,Bitmap.Config.ARGB_8888);
			
			Canvas canvas = new Canvas(newBmp);
			dawable.setBounds(0, 0, newBmp.getWidth(), newBmp.getHeight());
			dawable.draw(canvas);
			canvas.setBitmap(null);
			
			return newBmp;
		} catch (Exception e){
			e.printStackTrace();
		}
		
		return null;
	}
	
	// 获得数字图片
	public static Bitmap getNum(Context context, int number)
	{
		Resources res = context.getResources();
		Drawable bgDrawable = null;
		
		float customizeNumSize = res.getDimension(R.dimen.simple_number_text_size);
		
		// 根据数字大小选择背景图片
		if (number > 0 && number <= 9)
			bgDrawable = res.getDrawable(R.drawable.ic_number_bg_1);
		else if (9 < number && number <= 99)
			bgDrawable = res.getDrawable(R.drawable.ic_number_bg_2);
		else if (number > 99)
			bgDrawable = res.getDrawable(R.drawable.ic_number_bg_3);
		
		if (bgDrawable == null){
			return null;
		}
		
		int width = bgDrawable.getIntrinsicWidth();
		int height = bgDrawable.getIntrinsicHeight();
		
		Bitmap numberBmp = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
		Canvas canvas = new Canvas(numberBmp);
		Paint paint = new Paint();
		paint.setColor(-1);
		paint.setAntiAlias(true);
		
		// 先画背景
		bgDrawable.setBounds(0, 0, width, height);
		bgDrawable.draw(canvas);
		
		float numTextSize = customizeNumSize;
		
		String strNumer;
		if ((number > 0) && (number <= 99))
			strNumer = String.valueOf(number);
		else
			strNumer = "99+";
		
		paint.setTextSize(numTextSize);
		paint.setTextAlign(Paint.Align.CENTER);
		Paint.FontMetricsInt fontMetrics = paint.getFontMetricsInt();
		
		// 画数字文字
		float x = width/2.0F;
		float y = (height - (fontMetrics.bottom - fontMetrics.top))/2.0F - fontMetrics.top - 2.0F;
		canvas.drawText(strNumer, x, y, paint);
		
		return numberBmp;
	}
	
	// 设置透明度
	private static void setTransparent(int[] paramArrayOfInt, int paramInt1,
			int paramInt2, int paramInt3, int paramInt4, int paramInt5)
	{
		for (int i = paramInt3; i < paramInt5; i++)
			for (int j = paramInt2; j < paramInt4; j++)
			{
				int k = j + i * paramInt1;
				paramArrayOfInt[k] = (0xFFFFFF & paramArrayOfInt[k]);
			}
	}

	public static boolean isMirrorLanguage(){
		String str = Locale.getDefault().getLanguage();
		return ("fa".equals(str)) || ("ar".equals(str)) || ("iw".equals(str));
	}
	
	public static boolean startActivitySafely(Context context, View v, Intent intent, Object tag)
	{
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		try{
			boolean useLaunchAnimation = (v != null) && !intent.hasExtra(INTENT_EXTRA_IGNORE_LAUNCH_ANIMATION);
            if (useLaunchAnimation) {
                ActivityOptions opts = ActivityOptions.makeScaleUpAnimation(v, 0, 0,
                        v.getMeasuredWidth(), v.getMeasuredHeight());

                context.startActivity(intent, opts.toBundle());
            } else {
            	context.startActivity(intent);
            }
            return true;
		}catch (ActivityNotFoundException e) {
			Toast.makeText(context, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
	        Log.e(TAG, "Unable to launch. tag=" + tag + " intent=" + intent, e);
		}catch (SecurityException e){
			 Toast.makeText(context, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
	            Log.e(TAG, "Launcher does not have the permission to launch " + intent +
	                    ". Make sure to create a MAIN intent-filter for the corresponding activity " +
	                    "or use the exported attribute for this activity. "
	                    + "tag="+ tag + " intent=" + intent, e);
		}
		
		return false;
	}
	
	public static boolean startActivitySafely(Context context, Intent intent, Object tag)
	{
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		try{
			//ActivityOptions opts = ActivityOptions.makeCustomAnimation(context, R.anim.fade_in_fast, R.anim.fade_out_fast);
			//context.startActivity(intent, opts.toBundle());
			context.startActivity(intent);
			return true;
		}catch (ActivityNotFoundException e) {
			Toast.makeText(context, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
	        Log.e(TAG, "Unable to launch. tag=" + tag + " intent=" + intent, e);
		}catch (SecurityException e){
			 Toast.makeText(context, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
	            Log.e(TAG, "Launcher does not have the permission to launch " + intent +
	                    ". Make sure to create a MAIN intent-filter for the corresponding activity " +
	                    "or use the exported attribute for this activity. "
	                    + "tag="+ tag + " intent=" + intent, e);
		}
		
		return false;
	}
	
	public static void sendAccessibilityEvent(String msg)
	{
	   if (msg == null)
	     Log.i(TAG, "The AccessibilityEvent msg is null.");
	    
	    AccessibilityManager accessibilityManager = 
	    		LauncherApplication.getActiveInstance().getAccessibilityManager();
	    
	    if (accessibilityManager != null && accessibilityManager.isEnabled())
	    {
	    	AccessibilityEvent accessibilityEvent = AccessibilityEvent.obtain(32);
	    	accessibilityEvent.setPackageName("con.tozed.android.launcher");
	    	accessibilityEvent.getText().add(msg);
	    	accessibilityEvent.setAddedCount(msg.length());
	    	
	 	    accessibilityManager.sendAccessibilityEvent(accessibilityEvent);
	 	    
			try{
				accessibilityEvent.recycle();
			} catch (Exception e){
				Log.e(TAG, "Launcher.Utilities sendTapOutsideFolderAccessibilityEvent: event has been recycled");
			}
	    }
	}
	
	public static int getValidRows(int appsize)
	{
		int rows = appsize / 4;
		int append;
		
		if ((appsize % 4) > 0)
			append = 1;
		else
			append = 0;
		
		return rows + append;
	}
	
	public static boolean isCustomizePackage(String pkgName)
	{
		if (pkgName == null)
			return false;
		
		if (pkgName.equals("com.android.contacts") 
				|| pkgName.equals("com.android.mms")
				|| pkgName.equals("com.android.email")
				|| pkgName.equals("com.android.settings"))
		{
			return true;
		}
		
		return false;
	}

	public static boolean isCustomizePackage(String[] arrPkgName)
	{
		if (arrPkgName.length != 1)
			return false;
		
		return isCustomizePackage(arrPkgName[0]);
	}
	
	public static void updateCustomizeAppIcon(SimpleUILauncher simpleUiLauncher, String pkgName)
	{
		/*
		SimpleAllIdleAppsList allIdleAppsList = simpleUiLauncher.getMode().getAllIdleAppsList();
		
		if (allIdleAppsList != null)
		{
			allIdleAppsList.updatePackage(simpleUiLauncher, pkgName);
			
			if (allIdleAppsList.modified.size() > 0){
				ArrayList<SimpleApplicationInfo> appsModified = allIdleAppsList.modified;
				allIdleAppsList.modified = new ArrayList<SimpleApplicationInfo>();
				if (simpleUiLauncher.getWorkspace() != null)
					simpleUiLauncher.getWorkspace().updateCustomizeShortcuts(appsModified);
			}
		}
		*/
	}
	
    /**
     * 获取未接来电数
     */
    static int getMissedCallCount(Context context)
    {
    	final ContentResolver resolver = context.getContentResolver();
    	StringBuilder where = new StringBuilder();
    	where.append("type = ");
    	where.append(CallLog.Calls.MISSED_TYPE);
    	where.append(" AND New = 1");
    	
    	int nMissCall = 0;
    	Cursor c = null;
    	try
		{
    		c = resolver.query(CallLog.Calls.CONTENT_URI, 
        			new String[]{Calls._ID}, where.toString(), null, Calls.DEFAULT_SORT_ORDER);
        	if (c != null){
        		nMissCall = c.getCount();
        	}	
		} catch (Exception e){
			Log.e(TAG, e.getMessage(), e);
		} finally {
			if (c != null){
				c.close();
			}
		}
    	
    	//Log.d(TAG, "getMisscallCount nMissCall=" + nMissCall);
    	return nMissCall;
    }
    
    /**
     * 获取未读短信、彩信数
     */
    static int getUnreadMsgCount(Context context){
    	final ContentResolver resolver = context.getContentResolver();
    	
    	// content://sms/inbox
    	Uri uriSms = Uri.parse("content://sms");
    	Uri uriMms = Uri.parse("content://mms");
    	String where = "read = 0";
    	
    	int nUnReadSms = 0;
    	int nUnReadMms = 0;
    	Cursor c = null;
    	try
		{
    		c = resolver.query(uriSms, new String[]{BaseColumns._ID}, where, null, null);
        	if (c != null){
        		c.moveToFirst();
        		nUnReadSms = c.getCount();
        		c.close();
        	}	
        	
        	c = resolver.query(uriMms, new String[]{BaseColumns._ID}, where, null, null);
        	if (c != null){
        		c.moveToFirst();
        		nUnReadMms = c.getCount();
        	}	
		} catch (Exception e){
			// handle exception
			Log.e(TAG, e.getMessage(), e);
		} finally {
			if (c != null){
				c.close();
			}
		}
    	
    	Log.e(TAG, "getUnReadMsgCount nUnReadSms=" + nUnReadSms + " nUnReadMms=" + nUnReadMms);
    	return nUnReadSms + nUnReadMms;
    }
    
    static int getUnReadEmailCount(Context context){
    	// content://com.android.email.provider/message
    	return 0;
    }
    
    
}
